package message_api

import (
	"ginBolg/global"
	"ginBolg/models"
	"ginBolg/models/res"
	"github.com/gin-gonic/gin"
)

type MessageRequest struct {
	SendUserId uint   `json:"sendUserId" binding:"required"`
	RevUserId  uint   `json:"revUserId" binding:"required"`
	Content    string `json:"content" binding:"required"`
}

func (MessageApi) MessageCreateView(c *gin.Context) {
	var cr MessageRequest
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		res.FailWithError(err, &cr, c)
		return
	}
	var sendUser, recUser models.UserModel

	err = global.DB.Take(&sendUser, cr.SendUserId).Error
	if err != nil {
		res.Fail("发送人不存在", c)
		return
	}
	err = global.DB.Take(&recUser, cr.RevUserId).Error
	if err != nil {
		res.Fail("接收人不存在", c)
		return
	}
	err = global.DB.Create(&models.MessageModel{
		SendUserID:       cr.SendUserId,
		SendUserNickName: sendUser.NickName,
		SendUserAvatar:   sendUser.Avatar,
		RevUserID:        cr.RevUserId,
		RevUserNickName:  recUser.NickName,
		RevUserAvatar:    recUser.Avatar,
		IsRead:           false,
		Content:          cr.Content,
	}).Error
	if err != nil {
		res.Fail("消息发送失败", c)
		return
	}
	res.OkWithMessage("发送成功", c)
	return
}
